<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="600px"
    append-to-body
    :close-on-click-modal="false"
    @close="closeModal"
  >
    <el-tree
      ref="Tree"
      :data="treeData"
      show-checkbox
      node-key="id"
      :default-checked-keys="checkedKeys"
      :props="defaultProps"
    >
    </el-tree>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="confirm">确认选择</el-button>
      <el-button @click="closeModal">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getAcupointTree } from '@/api/saas/tcm.js'

export default {
  data() {
    return {
      title: "选择穴位",
      open: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      checkedKeys: []
    }
  },
  methods: {
    openModal(ids) {
      this.open = true;
      this.getTree();

      this.checkedKeys = ids;
    },
    getTree() {
      getAcupointTree().then(res => {
        const tree = [];
        res.data.forEach(parent=>{
          tree.push({
            id: `groupId_` + parent.groupId,
            label: parent.groupName,
            children: this.returnChild(parent.acupointList)
          })
        })

        for (let i = 0; i < tree.length; i++) {
          if(!tree[i].children.length){
            tree.splice(i, 1);
            i--;
          }
        }
        this.treeData = tree;
        console.log(JSON.parse(JSON.stringify(this.treeData)));
      })
    },
    returnChild(children) {
      const tree = [];
      if(children && children.length){
        children.forEach(child=>{
          tree.push({
            id: child.id,
            label: child.acupointName,
          })
        })
      }
      return tree;
    },
    closeModal() {
      Object.assign(this.$data, this.$options.data()); // 存在自定义校验规则不能重置data
    },
    confirm() {
      const ids = this.$refs.Tree.getCheckedNodes(true);
      if(!ids.length){
        this.$message.error('请选择穴位');
        return
      }else if(ids.length > 5){
        this.$message.error('最多仅支持选择5个穴位');
        return
      }

      this.$emit('change', ids);
      this.closeModal()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
